package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.BindingElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.mapper.member.MemberElderMapper;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IWeChetService;
import com.zzyl.nursing.vo.FamilyMemberElderPageVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author zbr
 * @date 2025-03-03
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private IWeChetService weChetService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private MemberElderMapper memberElderMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录
     *
     * @param userLoginRequestDto C端用户登录
     * @return 登录返回
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.获取openid
        String openId = weChetService.getOpenId(userLoginRequestDto.getCode());
        if (StrUtil.isBlank(openId)) {
            throw new BaseException("获取openId失败,非法微信用户");
        }
        // 2.根据openid查询用户信息
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        // 3.如果member不存在，则创建并赋予openid
        if (ObjectUtil.isNull(member)) {
            member = new FamilyMember();
            member.setOpenId(openId);
        }
        // 4.获取手机号
        String phoneNumber = weChetService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 5.新增或更新用户信息
        insertOrUpdate(member, phoneNumber);
        // 6.生成JWT，返回给前端
        String nickName = member.getName();
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",member.getId());
        claims.put("nickName", nickName);
        String token = tokenService.createToken(claims);
        // 7.封装数据
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(nickName);
        return loginVo;
    }

    /**
     * 更新或添加用户信息
     * @param member
     * @param phoneNumber
     */
    private void insertOrUpdate(FamilyMember member, String phoneNumber) {
        // 判断手机号是否修改
        if (!StrUtil.equals(member.getPhone(), phoneNumber)) {
            member.setPhone(phoneNumber);
        }
        // member存在id则为更新,不存在则为添加
        if (ObjectUtil.isNotNull(member.getId())) {
            this.updateById(member);
        } else {
            String memberPhone = member.getPhone();
            member.setName(DEFAULT_NICKNAME_PREFIX
                    .get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StrUtil.sub(memberPhone,memberPhone.length() - 4,memberPhone.length()));
            this.save(member);
        }
    }

    /**
     * 绑定老人
     *
     * @param bindingElderDto 绑定老人
     */
    @Override
    public void add(BindingElderDto bindingElderDto) {
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, bindingElderDto.getIdCard())
                .eq(Elder::getName, bindingElderDto.getName()).one();
        if (ObjectUtil.isNull(elder)) {
            throw new BaseException("养老院不存在该老人或者老人身份证输入错误");
        }
        Long userId = UserThreadLocal.get();
        List<Long> elderIds = memberElderMapper.findElderIdByMemberId(userId);
        if (elderIds.contains(elder.getId())) {
            throw new BaseException("当前老人已绑定");
        }
        FamilyMemberElder familyMemberElder = FamilyMemberElder
                .builder()
                .familyMemberId(userId)
                .elderId(elder.getId())
                .remark(bindingElderDto.getRemark())
                .build();
        memberElderMapper.insert(familyMemberElder);
    }

    /**
     * 获取用户绑定家人列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberElderVo> getMyFamilyMemberElder() {
        return memberElderMapper.getMyFamilyMemberElder(UserThreadLocal.get());
    }

    /**
     * 获取用户绑定家人分页列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<FamilyMemberElderPageVo> getMyFamilyMemberElderPage(Integer pageNum, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageHelper.startPage(pageNum, pageSize);

        List<FamilyMemberElderPageVo> myFamilyMemberElderPage = memberElderMapper.getMyFamilyMemberElderPage(userId);
        Page<FamilyMemberElderPageVo> p = (Page<FamilyMemberElderPageVo>) myFamilyMemberElderPage;
        return p.getResult();
    }
}
